package com.x.bpm.dao;

import com.x.bpm.model.*;
import com.x.framework.dao.BaseDao;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class BpmDao extends BaseDao {

private final static String selectInstanceStateEnumLisSql = "SELECT T1.STATE_KEY, T1.STATE_VALUE " +
        "FROM BPM_INSTANCE T1 " +
        "WHERE T1.APPLICATION_ID = ? " +
        "AND T1.INSTANCE_ID = ? ";
    public List<StateEnum> selectInstanceStateEnumLis(Instance instance) throws Exception {
        StringBuilder sql = new StringBuilder(selectInstanceStateEnumLisSql);
        List<Object> params = new ArrayList<>();
        params.add(instance.getApplicationId());
        params.add(instance.getInstanceId());
        return this.queryForList(sql.toString(), StateEnum.class, params);
    }

    private final static String selectStateEnumLisSql = "SELECT T1.STATE_KEY, T1.STATE_VALUE, T1.STATE_TEXT " +
            "FROM BPM_STATE_ENUM T1 " +
            "WHERE T1.APPLICATION_ID = ? " +
            "AND T1.STATE_KEY = ? ";
    public List<StateEnum> selectStateEnumLis(State state) throws Exception {
        StringBuilder sql = new StringBuilder(selectStateEnumLisSql);
        List<Object> params = new ArrayList<>();
        params.add(state.getApplicationId());
        params.add(state.getStateKey());
        return this.queryForList(sql.toString(), StateEnum.class, params);
    }

    private final static String selectRuleListSql = "SELECT * FROM BPM_RULE T1 WHERE APPLICATION_ID = ? AND PROCESS_ID = ? ";
    public List<Rule> selectRuleList(Rule rule) throws Exception {
        StringBuilder sql = new StringBuilder(selectRuleListSql);
        List<Object> params = new ArrayList();
        params.add(rule.getApplicationId());
        params.add(rule.getProcessId());
        return this.queryForList(sql.toString(), Rule.class, params);
    }

    private final static String selectOperationListSql = "SELECT DISTINCT T1.OPERATION_ID, T1.OPERATION_NAME, T1.OPERATION_URL " +
            "FROM BPM_OPERATION T1, BPM_RULE_OPERATION T2 " +
            "WHERE T1.APPLICATION_ID = T2.APPLICATION_ID " +
            "AND T1.OPERATION_ID = T2.OPERATION_ID " +
            "AND T2.APPLICATION_ID = ? " +
            "AND T2.PROCESS_ID = ? ";
    public List<Operation> selectOperationList(Rule rule, String ruleIds) throws Exception {
        StringBuilder sql = new StringBuilder(selectOperationListSql);
        sql.append("AND T2.RULE_ID IN (");
        sql.append(ruleIds);
        sql.append(")");
        List<Object> params = new ArrayList();
        params.add(rule.getApplicationId());
        params.add(rule.getProcessId());
        return this.queryForList(sql.toString(), Operation.class, params);
    }

}
